package com.yuchen.starssdkdemo;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.yuchen.starssdk.MqttServiceCallBack;
import com.yuchen.starssdk.RegistOnIotPlatformCallBack;
import com.yuchen.starssdk.StarsConfig;
import com.yuchen.starssdk.StarsSdkHelper;
import com.yuchen.starssdk.utils.LogUtils;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class RegisterMqttGatewayActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final StarsConfig config = new StarsConfig(
                StarsConfig.DeviceType.GatWay,  // 网关设备
                IotConfigConstant.tenantId,// 租户ID
                IotConfigConstant.productId,// 产品ID
                IotConfigConstant.productKey, // 产品秘钥
                4, //当前网关设备关联了几个子设备
                IotConfigConstant.subProductId); //子产品ID
        config.setDebug(true); // true 会打印注册日志
        config.setHeartBeatDuration(30000);
        StarsSdkHelper.getInstence().init(this,config);
        StarsSdkHelper.getInstence().registOnIotPlatformMqtt(new RegistOnIotPlatformCallBack() {
            @Override
            public void onSuccess(String jsonStr) {
                LogUtils.d(jsonStr);
            }

            @Override
            public void onError(String msg) {
                LogUtils.d(msg);
            }
        });


        StarsSdkHelper.getInstence().setMqttServiceCallBack(new MqttServiceCallBack() {
            @Override
            public void connectSuccess() {
                LogUtils.d("connectSuccess");
                StarsSdkHelper.getInstence().registOnIotPlatformMqtt();
            }

            @Override
            public void connectFail(Throwable e) {
                LogUtils.d("connectFail " + e.getMessage());
            }

            @Override
            public void connectLost(Throwable e) {
                LogUtils.d("connectLost " + e.getMessage());
            }

            @Override
            public void disconnected() {
                LogUtils.d("disconnected ");
            }

            @Override
            public void messageDeliveryComplete(IMqttDeliveryToken arg0) {
                try {
                    LogUtils.d("messageDeliveryComplete: "+new String(arg0.getMessage().getPayload()));
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {

            }
        });
        StarsSdkHelper.getInstence().connectMqtt();
    }
}